package com.yundasys.lab10designpattern.template;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @PACKAGE_NAME: com.yundasys.lab10designpattern.template
 * @NAME: JdbcTemplate
 * @USER: jiangta
 * @DATE: 2021/8/26
 * @TIME: 3:32 下午
 * @PROJECT_NAME: springboot-labs
 */
public abstract class JdbcTemplate {
    //template method
    public final Object execute(String sql) throws SQLException {

        Connection con = null;
        Statement stmt = null;
        try {

            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            Object result = doInStatement(rs);//abstract method
            return result;
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            throw ex;
        }
        finally {

            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(!con.isClosed()){
                    try {
                        con.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    //implements in subclass
    protected abstract Object doInStatement(ResultSet rs);
}
